/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Advance;
import com.jeeplus.modules.ap.entity.Recel;
import com.jeeplus.modules.ap.service.AdvanceService;
import com.jeeplus.modules.ap.service.RecelService;
import com.jeeplus.modules.fee.entity.Cope;
import com.jeeplus.modules.fee.entity.Js;
import com.jeeplus.modules.fee.service.CopeService;
import com.jeeplus.modules.fee.service.JsService;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.TmsWaybill;
import com.jeeplus.modules.tms.service.TmsWaybillService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 应付结算总报表Controller
 * @author 李超辉
 * @version 2019-02-14
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/paya")
public class PayaController extends BaseController {

	@Autowired
	private PayaService payaService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private LoadJsService loadJsService;
	@Autowired
	private HandlingService handlingService;
	@Autowired
	private JsService jsService;
	@Autowired
    private StoreBudgetService storeBudgetService;
	@Autowired
	private CopeService copeService;
	@Autowired
	private TmsWaybillService tmsWaybillService;
	@Autowired
	private AdvanceService advanceService;
	@Autowired
	private RecelService recelService;
	@ModelAttribute
	public Paya get(@RequestParam(required=false) String id) {
		Paya entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = payaService.get(id);
		}
		if (entity == null){
			entity = new Paya();
		}
		return entity;
	}
	/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "cx")
	public String cx(Date min, Date max, String pro) {
		jdbc.execute("delete from infof_paya");
		Calendar c = Calendar.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		Date i=min;
		Date mixx;
		Date maxx;
		if(min==null||max==null){
			return "false";
		}
		while (i.getTime()<max.getTime()) {
			mixx=i;
			Paya p=new Paya();
			p.setDate(i);
			c.setTime(i);
			c.add(Calendar.MONTH, 1);
			i=c.getTime();
			maxx=i;
			//仓租
			StoreBudget s=new StoreBudget();
			//装卸
			Handling h=new Handling();
			//运输
			Cope cope=new Cope();
			if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
				s.setPro(pro);
				h.setPro(pro);
				cope.setProject(pro);
			}else if(!UserUtils.getUseroffice().equals("总部")){
				s.setPro(UserUtils.getUseroffice());
				h.setPro(UserUtils.getUseroffice());
				cope.setProject(UserUtils.getUseroffice());
			}
			//仓租
			s.setRq(mixx);
			List<StoreBudget> rens=storeBudgetService.findList(s);
			double czje=0.0;
			double czjs=0.0;
			double czwjs=0.0;
			for(StoreBudget r:rens){
				czje+=Double.parseDouble(r.getZzc());
				czjs+=Double.parseDouble(r.getYf());
				czwjs+=Double.parseDouble(r.getWf());

			}
			p.setCzwf(nf.format(czwjs).replaceAll(",",""));
			p.setZc(nf.format(czje).replaceAll(",",""));
			p.setCzyf(nf.format(czjs).replaceAll(",",""));

			//装卸
			h.setDate(mixx);
			List<Handling> ls=handlingService.findList(h);
			double zxys=0.0;
			double zxkp=0.0;
			double zxwkp=0.0;
			for(Handling l:ls){
				zxys+=Double.parseDouble(l.getZzc());
				zxkp+=Double.parseDouble(l.getYf());
				zxwkp+=Double.parseDouble(l.getWf());
			}

			p.setZx(nf.format(zxys).replaceAll(",",""));
			p.setZxwf(nf.format(zxwkp).replaceAll(",",""));
			p.setZxyf(nf.format(zxkp).replaceAll(",",""));

			//运输
			cope.setDate(mixx);
			List<Cope> res=copeService.findList(cope);
			double ysys=0.0;
			double yskp=0.0;
			double yswkp=0.0;
			for(Cope r:res){
				ysys+=Double.parseDouble(r.getFreight());
				TmsWaybill t=new TmsWaybill();
				t.setPid(r.getPid());
				List<TmsWaybill> bills=tmsWaybillService.findList(t);
				for(TmsWaybill bill:bills){
                    Advance a=advanceService.findUniqueByProperty("bill",bill.getId());
                    if(a!=null){
                    	yskp+=Double.parseDouble( a.getSfzje());
					}
                    Recel cel=recelService.findUniqueByProperty("bill",bill.getId());
					if(cel!=null){
						yskp+=Double.parseDouble( cel.getSfzje());
					}
				}


			}
			p.setYs(nf.format(ysys).replaceAll(",",""));
			p.setYsyf(nf.format(yskp).replaceAll(",",""));
			p.setYswf(nf.format(ysys-yskp).replaceAll(",",""));
			double zys=ysys+czje+zxys;
			double zkp=yskp+czjs+zxkp;
			double zwkp=yswkp+czwjs+zxwkp;
			p.setZje(nf.format(zys).replaceAll(",",""));
			p.setZyf(nf.format(zkp).replaceAll(",",""));
			p.setZwf(nf.format(zwkp).replaceAll(",",""));
			payaService.save(p);
		}
		return "success";
	}
	/**
	 * 应付结算总报表列表页面
	 */
	@RequiresPermissions("infor:paya:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/payaList";
	}
	
		/**
	 * 应付结算总报表列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:paya:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Paya paya, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Paya> page = payaService.findPage(new Page<Paya>(request, response), paya); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑应付结算总报表表单页面
	 */
	@RequiresPermissions(value={"infor:paya:view","infor:paya:add","infor:paya:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Paya paya, Model model) {
		model.addAttribute("paya", paya);
		return "modules/infor/payaForm";
	}

	/**
	 * 保存应付结算总报表
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:paya:add","infor:paya:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Paya paya, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, paya)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		payaService.save(paya);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存应付结算总报表成功");
		return j;
	}
	
	/**
	 * 删除应付结算总报表
	 */
	@ResponseBody
	@RequiresPermissions("infor:paya:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Paya paya, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		payaService.delete(paya);
		j.setMsg("删除应付结算总报表成功");
		return j;
	}
	
	/**
	 * 批量删除应付结算总报表
	 */
	@ResponseBody
	@RequiresPermissions("infor:paya:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			payaService.delete(payaService.get(id));
		}
		j.setMsg("删除应付结算总报表成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:paya:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Paya paya, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应付结算总报表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Paya> page = payaService.findPage(new Page<Paya>(request, response, -1), paya);
    		new ExportExcel("应付结算总报表", Paya.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应付结算总报表记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:paya:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Paya> list = ei.getDataList(Paya.class);
			for (Paya paya : list){
				try{
					payaService.save(paya);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应付结算总报表记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应付结算总报表记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应付结算总报表失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/paya/?repage";
    }
	
	/**
	 * 下载导入应付结算总报表数据模板
	 */
	@RequiresPermissions("infor:paya:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应付结算总报表数据导入模板.xlsx";
    		List<Paya> list = Lists.newArrayList(); 
    		new ExportExcel("应付结算总报表数据", Paya.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/paya/?repage";
    }

}